package com.example.qihuibao.widget.dialog

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.Department
import com.example.qihuibao.bean.ReqUpdateDepartmentInfoBean
import com.example.qihuibao.bean.RspQueryDepartmentInfoBean
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.view.CommonRecyclerView
import com.example.qihuibao.widget.view.EdittextWithText

/**
 *@author: cww
 *@desc:企业信息操作
 *@date: 5/16/23 10:58 AM
 */
class DepartmentInfoUpdateDialog() : BaseDialogFragment(R.layout.dialog_department_info_update) {
    private var list:List<Department>? = null

    override fun initView() {
        mView?.findViewById<View>(R.id.iv_close)?.setOnClickListener { dismiss() }
        (activity as MainActivity).getMainViewModel().queryDepartmentInfo().observe(this) {
            if (it.RetCode == "0") {
                list = it.DepList
                mView?.findViewById<CommonRecyclerView>(R.id.rv_department)?.init(
                    R.layout.item_depinfo_update,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    list,
                    {parent, pos ->
                        parent.findViewById<EdittextWithText>(R.id.et_dep1_name).setText(getString(R.string.department_name1), list!![pos].DepName1?:"") {
                            list!![pos].DepName1 = it
                        }
                        parent.findViewById<EdittextWithText>(R.id.et_dep2_name).setText(getString(R.string.department_name2), list!![pos].DepName2?:"") {
                            list!![pos].DepName2 = it
                        }
                    }
                )
            }
        }
        mView?.findViewById<View>(R.id.btn_update)?.setOnClickListener { update() }
    }

    private fun update() {
        if (list.isNullOrEmpty()) {
            dismiss()
        }else {
            for (item in list!!) {
                if (item.DepName1.isNullOrEmpty()) {
                    activity?.toast("一级部门不能为空")
                    return
                }
                (activity as MainActivity).getMainViewModel().updateDepartmentInfo(ReqUpdateDepartmentInfoBean(item.DepID1,item.DepName1?:"",item.DepID2,item.DepName2)).observe(this) {
                    activity?.toast(if (it.RetCode == "0") "更新成功" else "更新失败")
                }
            }
        }
    }

}